import { fetchAllCategory } from '@/api/category.js';

export default {
	data() {
		return {
			currentId: 0,
			list: [],
			firstList: [],
			secondList: []
		};
	},
	onLoad() {
		this.loadData();
	},
	methods: {
		async loadData() {
			fetchAllCategory().then(response => {
				this.list = response.data;
				
				// 查找第一层级分类
				var temp ;
				var level0 = [] ; 
				for(var i=0; i<this.list.length; i++){
					if(this.list[i].level == 0){
						level0.push(this.list[i]);
					}
				}
				// 升序 排列
				level0.sort(function(a,b){
					return a.sort - b.sort;
				})
				
				//赋值一级分类数据
				this.firstList = level0;
				//手动触发第一个分类
				this.tabtap(level0[0]);
			})
		},
		//一级分类点击
		tabtap(item) {
			this.currentId = item.id;
			
			// 查找第二层级分类
			var temp ;
			var level1 = [] ; 
			for(var i=0; i<this.list.length; i++){
				//二级分类，且父ID是当前ID
				if(this.list[i].level == 1 && this.list[i].pId == this.currentId){
					level1.push(this.list[i]);
				}
			}
			
			// 升序 排列
			level1.sort(function(a,b){
				return a.sort - b.sort;
			})
			//赋值二级分类数据
			this.secondList = level1;
			
		},
		//导航到列表
		navToList(id,name) {
			uni.navigateTo({
				url: `/pages/category/list/list?categoryId=${id}&categoryName=${name}`
			})
		}
	}
}